﻿using HtmlAgilityPack;
using Prism.Commands;
using Prism.Mvvm;
using Prism.Services.Dialogs;
using System;
using System.Collections.Generic;
using System.Linq;

namespace HtmlAgilityPackAnalysis.ViewModels
{
    public class DescendantsModel : BindableBase, IDialogAware
    {
        public string Title => "下级元素展示";

        public event Action<IDialogResult> RequestClose;

        public List<HtmlNode> ChildNodes
        {
            get { return childNodes; }
            set { SetProperty(ref childNodes, value); }
        }

        private List<HtmlNode> childNodes;

        public HtmlNode FirstChild
        {
            get { return firstChild; }
            set { SetProperty(ref firstChild, value); }
        }

        public DelegateCommand SelectionCommand { get; set; }
        private HtmlNode firstChild;

        public string Attributes
        {
            get { return _attributes; }
            set { SetProperty(ref _attributes, value); }
        }

        private string _attributes;

        private void Selection()
        {
            if (FirstChild != null)
            {
                Attributes = $"{{{Environment.NewLine}{string.Join(Environment.NewLine, FirstChild.Attributes.Select(a => $"{a.Name}: {a.Value}"))}{Environment.NewLine}}}";
            }
            else
            {
                Attributes = string.Empty;
            }
        }

        public DescendantsModel()
        {
            SelectionCommand = new DelegateCommand(Selection);
        }

        public bool CanCloseDialog()
        {
            return true;
        }

        public void OnDialogClosed()
        {
        }

        public void OnDialogOpened(IDialogParameters parameters)
        {
            ChildNodes = parameters.GetValue<IEnumerable<HtmlNode>>("data").ToList();
            FirstChild = ChildNodes.FirstOrDefault();
            Selection();
        }
    }
}